<template>
  <div class="stock-monitor">
    <!-- 搜索与新增 -->
    <el-card class="mb-4" shadow="never">
      <el-form :inline="true" :model="searchForm" size="small">
        <el-form-item label="物料名称">
          <el-input v-model="searchForm.name" clearable placeholder="物料名称"/>
        </el-form-item>
        <el-form-item label="物料编码">
          <el-input v-model="searchForm.code" clearable placeholder="物料编码"/>
        </el-form-item>
        <el-form-item label="类别">
          <el-select v-model="searchForm.category" clearable placeholder="全部类别" style="width:120px">
            <el-option v-for="cat in categories" :key="cat" :label="cat" :value="cat"/>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="success" @click="openDialog('add')">新增物料</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <!-- 库存表格 -->
    <el-table :data="filteredData" border style="width:100%;">
      <el-table-column prop="name" label="物料名称" width="140"/>
      <el-table-column prop="code" label="物料编码" width="130"/>
      <el-table-column prop="category" label="类别" width="100"/>
      <el-table-column prop="unit" label="单位" width="80"/>
      <el-table-column prop="stock" label="实时库存" width="110">
        <template #default="{ row }">
          <span :style="{color: row.stock < row.warning ? '#F56C6C':''}">
            {{ row.stock }}
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="warning" label="预警库存" width="110"/>
      <el-table-column prop="occupied" label="占用数量" width="100"/>
      <el-table-column prop="onway" label="在途数量" width="100"/>
      <el-table-column label="操作" width="150">
        <template #default="{ row, $index }">
          <el-button size="small" @click="openDialog('edit', row, $index)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete($index)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 库存趋势图 -->
    <el-card class="mt-4" shadow="never">
      <div class="flex items-center mb-2">
        <span style="font-weight:500">库存趋势：</span>
        <el-select v-model="trendMatCode" placeholder="选择物料" style="width:180px; margin-left:12px">
          <el-option v-for="row in filteredData" :key="row.code" :label="row.name" :value="row.code"/>
        </el-select>
      </div>
      <div ref="chartRef" style="width:100%;height:300px"></div>
    </el-card>

    <!-- 新增/编辑弹窗 -->
    <el-dialog :title="dialogMode==='add'?'新增物料':'编辑物料'" v-model="showDialog" width="430px">
      <el-form :model="dialogForm" :rules="dialogRules" ref="dialogFormRef" label-width="90px">
        <el-form-item label="物料名称" prop="name">
          <el-input v-model="dialogForm.name" />
        </el-form-item>
        <el-form-item label="物料编码" prop="code">
          <el-input v-model="dialogForm.code" :disabled="dialogMode==='edit'" />
        </el-form-item>
        <el-form-item label="类别" prop="category">
          <el-select v-model="dialogForm.category" style="width:100%">
            <el-option v-for="cat in categories" :key="cat" :label="cat" :value="cat"/>
          </el-select>
        </el-form-item>
        <el-form-item label="单位" prop="unit">
          <el-input v-model="dialogForm.unit" />
        </el-form-item>
        <el-form-item label="实时库存" prop="stock">
          <el-input-number v-model="dialogForm.stock" :min="0" style="width:100%"/>
        </el-form-item>
        <el-form-item label="预警库存" prop="warning">
          <el-input-number v-model="dialogForm.warning" :min="0" style="width:100%"/>
        </el-form-item>
        <el-form-item label="占用数量" prop="occupied">
          <el-input-number v-model="dialogForm.occupied" :min="0" style="width:100%"/>
        </el-form-item>
        <el-form-item label="在途数量" prop="onway">
          <el-input-number v-model="dialogForm.onway" :min="0" style="width:100%"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showDialog = false">取消</el-button>
        <el-button type="primary" @click="submitDialog">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, nextTick, onMounted, watch } from 'vue'
import { ElMessage } from 'element-plus'
import * as echarts from 'echarts'

const categories = ['原料', '辅料', '包材', '成品']
const allData = ref(generateMock())
function generateMock() {
  const mat = ['对乙酰氨基酚', '头孢拉定原料', '维生素C粉', '葡萄糖', '乳糖', '硬脂酸镁', '阿莫西林', '氯化钠', '塑料瓶', '说明书', '纸箱']
  const cat = ['原料', '辅料', '包材', '成品']
  const arr = []
  for (let i = 0; i < 11; i++) {
    arr.push({
      name: mat[i],
      code: 'MAT' + (10000 + i),
      category: cat[i % 4],
      unit: ['kg', 'kg', 'kg', 'kg', 'kg', 'kg', 'kg', 'kg', '个', '份', '箱'][i],
      stock: Math.floor(Math.random() * 3000) + 100,
      warning: Math.floor(Math.random() * 400) + 50,
      occupied: Math.floor(Math.random() * 200),
      onway: Math.floor(Math.random() * 100)
    })
  }
  return arr
}

// 搜索
const searchForm = reactive({ name: '', code: '', category: '' })
const filteredData = computed(() =>
  allData.value.filter(row =>
    (!searchForm.name || row.name.includes(searchForm.name)) &&
    (!searchForm.code || row.code.includes(searchForm.code)) &&
    (!searchForm.category || row.category === searchForm.category)
  )
)
function handleSearch() {}
function resetSearch() {
  searchForm.name = ''
  searchForm.code = ''
  searchForm.category = ''
}

// 增删改查
const showDialog = ref(false)
const dialogMode = ref('add')
const dialogForm = reactive({
  name: '', code: '', category: '', unit: '', stock: 0, warning: 0, occupied: 0, onway: 0
})
const dialogRules = {
  name: [{ required: true, message: '必填', trigger: 'blur' }],
  code: [{ required: true, message: '必填', trigger: 'blur' }],
  category: [{ required: true, message: '必填', trigger: 'change' }],
  unit: [{ required: true, message: '必填', trigger: 'blur' }]
}
const dialogFormRef = ref()
let editingIdx = -1
function openDialog(mode, row, idx) {
  dialogMode.value = mode
  if (mode === 'add') {
    Object.assign(dialogForm, { name: '', code: '', category: '', unit: '', stock: 0, warning: 0, occupied: 0, onway: 0 })
  } else {
    Object.assign(dialogForm, { ...row })
    editingIdx = idx
  }
  showDialog.value = true
  nextTick(() => dialogFormRef.value && dialogFormRef.value.clearValidate())
}
function submitDialog() {
  dialogFormRef.value.validate(valid => {
    if (!valid) return
    if (dialogMode.value === 'add') {
      allData.value.unshift({ ...dialogForm })
      ElMessage.success('新增成功')
    } else {
      allData.value.splice(editingIdx, 1, { ...dialogForm })
      ElMessage.success('编辑成功')
    }
    showDialog.value = false
  })
}
function handleDelete(idx) {
  allData.value.splice(idx, 1)
  ElMessage.success('已删除')
}

// ---- 库存趋势图 ----
const chartRef = ref()
const trendMatCode = ref('')
const trendDataMap = ref({})
onMounted(() => {
  // 初次选第一个物料
  if (filteredData.value.length) trendMatCode.value = filteredData.value[0].code
})
watch(filteredData, v => {
  if (v.length && !v.find(row => row.code === trendMatCode.value)) {
    trendMatCode.value = v[0].code
  }
})
watch(trendMatCode, () => { nextTick(drawChart) })
onMounted(() => { nextTick(drawChart) })
watch([filteredData, trendMatCode], () => { nextTick(drawChart) })

function getTrend(code) {
  // 生成30天趋势，首日和当前库存一致
  if (!trendDataMap.value[code]) {
    const mat = allData.value.find(row => row.code === code)
    if (!mat) return { x: [], y: [] }
    let arr = []
    let curr = mat.stock
    for (let i = 29; i >= 0; i--) {
      let delta = Math.floor(Math.random() * 40) - 20
      arr.push(Math.max(0, curr + delta))
      curr += delta
    }
    arr = arr.reverse()
    trendDataMap.value[code] = {
      x: Array.from({ length: 30 }, (_, k) =>
        (new Date(Date.now() - (29 - k) * 24 * 3600 * 1000)).toISOString().slice(5, 10)
      ),
      y: arr
    }
  }
  return trendDataMap.value[code]
}

function drawChart() {
  if (!chartRef.value || !trendMatCode.value) return
  const chart = echarts.init(chartRef.value)
  const trend = getTrend(trendMatCode.value)
  chart.setOption({
    tooltip: { trigger: 'axis' },
    grid: { left: 40, right: 20, bottom: 40, top: 40 },
    xAxis: { type: 'category', data: trend.x, axisLabel: { interval: 4 } },
    yAxis: { type: 'value', min: 0 },
    series: [{
      type: 'line',
      data: trend.y,
      smooth: true,
      areaStyle: { opacity: 0.14 }
    }]
  })
  chart.resize()
}
</script>

<style scoped>
.stock-monitor {
  padding: 20px 16px;
}
.mb-4 { margin-bottom: 16px;}
.mt-4 { margin-top: 20px;}
.flex { display: flex; align-items: center; }
.items-center { align-items: center; }
.mb-2 { margin-bottom: 8px;}
</style>
